/* enum */
import ComponentNameEnum from '@model/enum/ComponentNameEnum'
/* model */
import { ChartRepertory } from '@model/param/out/Chart'
/* vue */
// @ts-ignore
import { ComponentInstance, ComponentRenderProxy, defineComponent, onMounted, Ref, ref } from 'vue'
// API
import * as ReportApi from '@src/api/ReportApi';
import { CommonComponentInstance } from '@model/VC'

type HandlerRepertoryChangeFunctionType = (value: string) => void;

interface ChartRepertorySelectSetupState {
  // 仓库表改变事件
  handlerRepertoryChange: HandlerRepertoryChangeFunctionType;
  // 图表仓库列表
  repertoryList: Ref<ChartRepertory[]>;
}

enum ChartRepertorySelectEventEnum {
  Input = 'input'
}

export type ChartRepertorySelectProps = {
  // 仓库id
  value: string;
}

export type ChartRepertorySelectInstance = ComponentInstance & ChartRepertorySelectSetupState
export type ChartTaskTypeSelectVM = ComponentRenderProxy<ChartRepertorySelectProps> & CommonComponentInstance

export default defineComponent<ChartRepertorySelectProps,ChartRepertorySelectSetupState>({
	name: ComponentNameEnum.ChartRepertorySelect,
	props: {
		value: {
			type: String,
			default: ''
		}
	},
	setup(props: ChartRepertorySelectProps, { emit }) {
		let repertoryList: Ref<ChartRepertory[]> = ref([])

		/**
     * @description: 获取仓库列表
    */
		const fetchChartRepertory: VoidFunction = async () => {
      try {
        const result = await ReportApi.getRepertory()
			  repertoryList.value = result?.data || []
      } catch(error) {
        console.log(error)
      }
		}

		/** 
     * @description: 仓库列表改变事件
    */
		 const handlerRepertoryChange: HandlerRepertoryChangeFunctionType = (value: string) => {
      emit(ChartRepertorySelectEventEnum.Input, value)
    }

		onMounted(() => {
      fetchChartRepertory()
    })

		return {
			repertoryList,
			handlerRepertoryChange
		}
	},
	render() {
		return (
			<el-select
        value={this.value}
        clearable
        placeholder="全部仓库"
				class="task-span"
        onInput={this.handlerRepertoryChange}
      >
        {
          this.repertoryList.map((repertory: ChartRepertory) => {
            return (
              <el-option
                key={repertory.id}
                label={repertory.name}
                value={repertory.id}
              >
              </el-option>
            )
          })
        }
      </el-select>
		)
	}
})